<template>
  <div class="app_main">
    <div class="header">{{type == 2 ? '销售单(换画)撤单' : '销售单撤单'}}</div>
    <div class="table_box">
      <el-form ref="cuForm" v-loading="formLoading" :model="cuForm" :rules="rules" :disabled="formDisabled">
        <table class="mailTable">
          <tr v-if="cuForm.contract_id">
            <td colspan="8" style="border: none">
              <div style="text-align: right">
                <el-button type="primary" size="mini" :disabled="false" @click="showContractDialog">查看关联的合同</el-button>
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="8" style="border: none">
              <div class="flex flex-no-wrap justify-between">
                <div style="font-weight: bold">
                  合同编号:
                  <span :class="cuForm.contract_num ? 'text-red' : '' ">{{ cuForm.contract_num ? cuForm.contract_num : '选择完合同自动填充' }}</span>
                </div>
                <div style="text-align: right;font-weight: bold">
                  <span style="margin-right: 20px">填表日期:</span>
                  <span>{{ cuForm.fill_date|formatDate }}</span>
                </div>
              </div>
            </td>
          </tr>
          <tr class="firstTr">
            <td colspan="2" class="firstTd tip_td">
              <span class="tip">*</span>项目名称
            </td>
            <td colspan="2" class="column content_td">
              <el-form-item prop="customer_id">
                <el-select v-model="cuForm.customer_id" :disabled="is_update" style="width: 100%" filterable @change="customerChange">
                  <el-option v-for="item in customerArr" :key="item.id" :value="item.id" :label="item.name"/>
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              <span class="tip">*</span>客户合同名称
            </td>
            <td colspan="3" class="column content_td">
              <el-form-item prop="contract_id">
                <el-select v-model="cuForm.contract" :disabled="is_update" style="width: 100%" filterable value-key="id" @change="contractChange">
                  <el-tooltip v-for="(item,i) in contractArr" :key="item.id" placement="left">
                    <div slot="content">
                      <div>合同金额: {{ item.discounted_price + '元'}}</div>
                      <div v-if="item.contractMediaPriceList && item.contractMediaPriceList.length">
                        自营资源:
                      </div>
                      <div v-if="item.contractMediaPriceList && item.contractMediaPriceList.length"
                           v-for="(media,index) in item.contractMediaPriceList" :key="i+'_'+index+'_'+media.type">
                        |--{{ media.media_type_name + ':' + media.amount + '元' }}
                      </div>
                      <div v-if="item.contractMediaPriceProxyList && item.contractMediaPriceProxyList.length">
                        代理资源:
                      </div>
                      <div v-if="item.contractMediaPriceProxyList && item.contractMediaPriceProxyList.length"
                           v-for="(media,index) in item.contractMediaPriceProxyList" :key="i+'_'+index+'_'+media.type">
                        |--{{ media.media_type_name + ':' + media.amount + '元' }}
                      </div>
                    </div>
                    <el-option :value="item" :label="item.part_a+'——'+item.contract_num+'（'+item.contract_begin_date+' ~ '+item.contract_end_date+'）'"/>
                  </el-tooltip>
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td colspan="2" class="firstTd tip_td"><span class="tip">*</span>公司名称</td>
            <td colspan="2" class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_id" style="width: 100%">
                  <el-option v-for="item in companyArr" :key="item.id" :value="item.id" :label="item.head"/>
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td" >合同金额</td>
            <td class="column" style="width: 15%">
              {{ contractAmount ? contractAmount + '元' : contractAmount }}
            </td>
            <td class=" tip_td" >折扣</td>
            <td class="column" style="width: 15%">
              <el-form-item prop="discount">
                <el-input v-model="cuForm.discount" type="number" step="0.01" placeholder="自动计算" readonly >
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td colspan="2" class="firstTd tip_td">累计已执行金额</td>
            <td colspan="2" class="column content_td">
              <el-form-item prop="totalExecutedAmount">
                {{ totalExecutedAmount !== null && totalExecutedAmount !== undefined ? totalExecutedAmount + '元' : '' }}
              </el-form-item>
            </td>
            <td class="tip_td" >本次广告发布金额</td>
            <td colspan="3" class="column content_td">
              <el-form-item prop="release_amount">
                <el-input v-model="cuForm.release_amount" type="number" step="0.01" placeholder="请输入广告发布金额">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </td>
          </tr>
          </table>
          <table class="mailTable">
          <tr class="firstTr">
            <td class="firstTd tip_td">自营项目</td>
            <td class="column" colspan="3" style="text-align: left;padding: 0;">
              <div style="max-width: 100%;overflow: auto">
                <el-table :header-row-style="{'line-height':'38px'}" class="fill_table" :data="cuForm.mediaDetailList"
                          stripe border style="width: 100%;">
                <el-table-column label="媒体类型" align="center">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'mediaDetailList.'+scope.$index+'.media_type_id'"
                                    :rules="{required: true, message: '媒体类型不能为空', trigger: 'change'}">
                        <el-select v-model="scope.row.media_type_id" size="mini" placeholder="请选择媒体类型" @change="(val)=>{
                          mediaTypeChange(scope.$index,val)}">
                          <el-option v-for="item in mediaTypeArr" :key="item.id" :value="item.id" :label="item.name"/>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="规格" align="center">
                    <template slot-scope="scope">
                      <el-form-item style="margin: 18px 0" :prop="'mediaDetailList.'+scope.$index+'.media_type_spec_id'">
                        <el-select v-model="scope.row.media_type_spec_id" size="mini" placeholder="请选择规格">
                          <el-option v-for="(item,index) in scope.row.media_type_spec_arr" :key="index" :value="item" :label="item"/>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="执行时间" align="center"  width="320px">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'mediaDetailList.'+scope.$index+'.duration'"
                                    :rules="{required: true, message: '执行时间不能为空', trigger: 'change'}">
                        <el-date-picker v-model="scope.row.duration" type="daterange" size="mini" range-separator="至"
                                                      start-placeholder="开始日期"
                                                      end-placeholder="结束日期"
                                                      value-format="yyyy-MM-dd"
                                                      format="yyyy年MM月dd日"
                                                      :clearable="false"
                                                      style="width: 100%;" @change="(val) => {executeTimeChange(val,scope.row)}"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="周期" align="center"  width="80px">
                    <template slot-scope="scope">
                      <el-form-item style="margin: 18px 0" :prop="'mediaDetailList.'+scope.$index+'.media_cycle'">
                        <el-input v-model="scope.row.media_cycle" type="number" size="mini" placeholder="请输入周期" />
                        <el-select v-model="scope.row.media_cycle_unit" size="mini" placeholder="请选择单位">
                          <el-option v-for="(unit,index) in media_cycle_unit_arr" :key="index" :value="unit.key" :label="unit.name"/>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="合同数量" align="center" width="100px">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'mediaDetailList.'+scope.$index+'.contract_quantity'">
                        <span style="line-height: 38px">{{scope.row.contract_quantity}}</span>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="已执行数" align="center" width="100px">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'mediaDetailList.'+scope.$index+'.total_executed_quantity'">
                        <span style="line-height: 38px">{{scope.row.total_executed_quantity}}</span>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="执行数量" align="center" width="100px">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'mediaDetailList.'+scope.$index+'.quantity'">
                        <el-input v-model="scope.row.quantity" size="mini" placeholder="请输入数量" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="合同单价" align="center" width="100px">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'mediaDetailList.'+scope.$index+'.contract_price'">
                        <el-input v-model="scope.row.contract_price" size="mini" placeholder="合同单价" readonly/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="执行单价" align="center">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'mediaDetailList.'+scope.$index+'.price'">
                        <el-input v-model="scope.row.price" size="mini" placeholder="单价自动计算" readonly :class="scope.row.class_name"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="金额(元)" align="center">
                    <template slot-scope="scope">
                      <el-form-item :prop="'mediaDetailList.'+scope.$index+'.amount'"
                                    :rules="{required: true, message: '金额不能为空', trigger: 'blur'}">
                        <el-input v-model="scope.row.amount" type="number" step="0.01" size="mini" placeholder="请输入金额">
                        </el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="!is_created" label="市场单生成" align="center" >
                    <template slot-scope="scope">
                      <el-link type="primary" v-if="scope.row.is_market > 0" @click="lookMarketDetail(scope.row.is_market,true)">已生成</el-link>
                      <el-link type="success" v-else @click="lookMarketDetail(scope.row.bill_sale_detail_id,false)">待生成</el-link>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="!formDisabled" width="50" align="center">
                    <template slot="header">
                      <i style="color: #00c300;font-size: 20px;line-height: 38px" class="el-icon-circle-plus-outline" @click="selfMediaAdd"/>
                    </template>
                    <template slot-scope="scope">
                      <i style="color: #da0000;font-size: 20px;line-height: 38px" class="el-icon-remove-outline"
                         @click="selfMediaDeleteByIndex(scope.$index)"/>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </td>
          </tr>
          </table>
          <table class="mailTable">
          <tr class="firstTr">
            <td class="firstTd tip_td">代理项目</td>
            <td class="column" colspan="3" style="text-align: left;padding: 0;">
              <div style="max-width: 100%;overflow: auto">
                <el-table :header-row-style="{'line-height':'38px'}" class="fill_table" :data="cuForm.proxyMediaDetailList"
                          stripe border style="width: 100%;">
                <el-table-column label="媒体类型" align="center">
                    <template slot-scope="scope">
                      <el-form-item :prop="'proxyMediaDetailList.'+scope.$index+'.proxy_media_type'"
                                    :rules="{required: true, message: '代理媒体不能为空', trigger: 'blur'}">
                        <el-input v-model="scope.row.proxy_media_type" size="mini" placeholder="请输入代理媒体"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="媒体规格" align="center">
                    <template slot-scope="scope">
                      <el-form-item :prop="'proxyMediaDetailList.'+scope.$index+'.proxy_media_type_spec'">
                        <el-input v-model="scope.row.proxy_media_type_spec" size="mini" placeholder="请输入代理媒体"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="执行时间" align="center"  width="380px">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'proxyMediaDetailList.'+scope.$index+'.duration'"
                                    :rules="{required: true, message: '执行时间不能为空', trigger: 'change'}">
                        <el-date-picker v-model="scope.row.duration" type="daterange" size="mini" range-separator="至"
                                                      start-placeholder="开始日期"
                                                      end-placeholder="结束日期"
                                                      value-format="yyyy-MM-dd"
                                                      format="yyyy年MM月dd日"
                                                      :clearable="false"
                                                      style="width: 100%;" @change="(val) => {executeTimeChange(val,scope.row)}"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="周期" align="center"  width="80px">
                    <template slot-scope="scope">
                      <el-form-item style="margin: 18px 0" :prop="'proxyMediaDetailList.'+scope.$index+'.proxy_media_cycle'">
                        <el-input v-model="scope.row.proxy_media_cycle" type="number" size="mini" placeholder="请输入周期" />
                        <el-select v-model="scope.row.proxy_media_cycle_unit" size="mini" placeholder="请选择单位">
                          <el-option v-for="(unit,index) in media_cycle_unit_arr" :key="index" :value="unit.key" :label="unit.name"/>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="执行数量" align="center">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'proxyMediaDetailList.'+scope.$index+'.proxy_quantity'">
                        <el-input v-model="scope.row.proxy_quantity" size="mini" placeholder="请输入数量"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="执行单价" align="center">
                    <template slot-scope="scope">
                      <el-form-item  :prop="'proxyMediaDetailList.'+scope.$index+'.proxy_price'">
                        <el-input v-model="scope.row.proxy_price" size="mini" placeholder="单价自动计算" readonly/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="金额(元)" align="center">
                    <template slot-scope="scope">
                      <el-form-item :prop="'proxyMediaDetailList.'+scope.$index+'.proxy_amount'"
                                    :rules="{required: true, message: '金额不能为空', trigger: 'blur'}">
                        <el-input v-model="scope.row.proxy_amount" type="number" step="0.01" size="mini" placeholder="请输入金额">
                        </el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="!formDisabled" width="50" align="center">
                    <template slot="header">
                      <i style="color: #00c300;font-size: 20px;line-height: 38px" class="el-icon-circle-plus-outline" @click="proxyMediaAdd"/>
                    </template>
                    <template slot-scope="scope">
                      <i style="color: #da0000;font-size: 20px;line-height: 38px" class="el-icon-remove-outline" @click="proxyMediaDeleteByIndex(scope.$index)"/>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </td>
          </tr>
          </table>
          <table class="mailTable">
            <tr class="firstTr">
            <td class="tip_td firstTd" rowspan="3"><span class="tip">*</span>是否置换</td>
            <td class="column content_td" rowspan="3">
              <el-form-item prop="need_replace">
                <el-radio-group v-model="cuForm.need_replace">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </td>
           <td class="tip_td">本次执行总金额</td>
           <td class="column content_td">{{ cuForm.execute_amount }}元</td>
         </tr>
          <tr>
            <td class="tip_td">物品金额</td>
            <td class="column content_td">
              <el-form-item prop="item_amount">
                <el-input v-model="cuForm.item_amount" type="number" step="0.01" placeholder="请输入物品金额">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">现金金额</td>
            <td class="column content_td">
              <el-form-item prop="cash_amount">
                <el-input v-model="cuForm.cash_amount" type="number" step="0.01" placeholder="请输入消费金额">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="firstTd tip_td">
              <span class="tip">*</span>收款时间
            </td>
            <td class="column content_td">
              <el-form-item prop="collection_time">
                <el-date-picker
                  v-model="cuForm.collection_time"
                  type="date"
                  placeholder="请选择收款时间"
                  value-format="yyyy-MM-dd"
                  format="yyyy年MM月dd日"
                  style="width: 100%"/>
              </el-form-item>
            </td>
            <td class="tip_td"><span class="tip">*</span>是否开票</td>
            <td class="column content_td">
              <el-form-item prop="need_invoice">
                <el-radio-group v-model="cuForm.need_invoice">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td firstTd">备注</td>
            <td class="column" colspan="3">
              <div style="padding: 10px 0">
                <el-input v-model="cuForm.memo" type="textarea" placeholder="请输入备注" :rows="4"/>
              </div>
            </td>
          </tr>
        </table>
      </el-form>
    </div>
    <div style="margin: 20px auto">
      <FlowBtnRow :form-name="'cuCancel'" :is-new-data="is_created" :can-check="cuCancel.can_check"
                  :is-applyer="cuCancel.flow_applyer_id == user_id" :flow-status="cuCancel.flow_status"
                  :flow-type="24" :data-id="(params || {}).id || ((params || {}).handle_param || {}).id"
                  @pass="pass"
                  @returnBack="reject"/>
    </div>
    <contract-dialog ref="contractDialog" :contract_id="cuForm.contract_id"/>
  </div>
</template>

<script>
import FlowBtnRow from '@/components/FlowBtnRow/index'
import { get_company } from '@/api/system/department'
import { detail as contractDetail, list_by_customer_id, listByCustomerId } from '@/api/contract'
import {
  actual_delete,
  pass,
  remove,
  return_back,
  beginNew,
  saveNew,
  detailNew,
  list_media_type_spec_price,
  cancelDetail,
  cancelPass,
  cancelReject
} from '@/api/saleOrder'
import { formatDate, formatDateByFmt, generateUUID, getDaysBetween } from '@/utils/util'
import { add, divide, multiply } from '@/utils/amount'
import { company_list_all, list_all } from '@/api/customer/customer'
import { cloneDeep } from 'lodash/lang'
import ContractDialog from '@/views/business/contract/components/ContractDialog'
import { list_media_types } from '@/api/building/building'
import { listTypeSpecByMediaTypeId } from '@/api/media/specs'

export default {
  name: 'Detail',
  components: {ContractDialog, FlowBtnRow},
  filters: {
    formatDate(time) {
      if (time) {
        return formatDateByFmt(time, 'yyyy年MM月dd日')
      }
    }
  },
  data() {
    return {
      params: {},
      is_created: false,
      is_update: false,
      saleBillId: null,//销售单ID
      companyArr: [],
      contractArr: [],
      contractAmount: null,
      customerArr: [],
      mediaTypeArr: [],
      mediaTypeSpecPriceArr: [],
      formLoading: false,
      type: 1,// 销售单类型 1普通 2换画
      media_cycle_unit_arr: [
        {"key":"day", "name": "天"},
        {"key":"week", "name": "周"},
        {"key":"month", "name": "月"}
      ],
      cuCancel: {},
      cuForm: {
        fill_date: formatDate(new Date()),// 填表日期
        customer_id: null,// 客户ID
        contract_id: null,// 合同ID
        contract_num: null,// 合同编号
        dept_id: null,// 分公司id
        release_amount: null, // 本次发布金额
        execute_amount: null,// 本次执行金额
        need_replace: null,// 是否置换：1：是，0：否
        item_amount: null,// 物品金额
        cash_amount: null,// 现金金额
        collection_time: null,// 收款时间
        need_invoice: null,// 是否开发票：1：是，0：否
        memo: null,// 备注
        mediaDetailList: [],// 自营媒体资源明细
        proxyMediaDetailList: [],// 代理媒体资源明细
        self_execute_amount: null,// 自营本次执行金额
        proxy_execute_amount: null,// 代理本次执行金额
        total_executed_amount: null,// 累计总执行金额
        // 斟酌是否需要
        discount: null,// 折扣
        accrued_amount: null,// 计提额
        replace_amount: null,// 本次换画面金额
      },
      contractMediaTypeCount: [],// 合同媒体类型数量
      contractMediaTypePrice: [],// 合同媒体类型数量
      contractMediaDetailList: [],// 合同自营资源
      contractProxyMediaDetailList: [],// 合同代理资源
      totalExecutedAmount: null,// 累计已执行金额
      totalSelfExecutedAmount: null,// 自营累计执行金额
      totalProxyExecutedAmount: null,// 代理累计执行金额
      errorData: {},
      rules: {
        customer_id: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        contract_id: [
          { required: true, message: '请选择合同', trigger: 'change' }
        ],
        dept_id: [
          { required: true, message: '请选择所属公司', trigger: 'change' }
        ],
        need_replace: [
          { required: true, message: '请选择是否置换', trigger: 'change' }
        ],
        need_invoice: [
          { required: true, message: '请选择是否开票', trigger: 'change' }
        ],
        collection_time: [
          { required: true, message: '请选择收款时间', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 当前用户ID
    user_id() { return this.$store.state.user.id },
    // 执行金额 = 发布金额 + 置换金额
    execute_amount() {
      let tmp = 0
      if (this.cuForm.release_amount) {
        tmp = add(this.cuForm.release_amount, tmp)
      }
      if (this.cuForm.replace_amount) {
        tmp = add(this.cuForm.replace_amount, tmp)
      }
      console.log(tmp)
      return tmp
    },
    // 表单禁用设置判断
    formDisabled() { return this.cuForm.flow_status == 3 || this.cuForm.flow_status == 4 },
    // 计提额计算 计提额 = 执行金额 * 计提百分比
    commission() {
      if (this.execute_amount && this.cuForm.accrued_amount) {
        const a = divide(this.cuForm.accrued_amount, '100')
        const sum = multiply(a, this.execute_amount)
        return sum + '元'
      } else {
        return undefined
      }
    },
    // 是否只有电梯智能框类型
    onlyElevatorSmartFrame() { // 是否只有电梯智能框类型
      if (this.media_type_count_amount_arr && this.media_type_count_amount_arr.length) {
        return this.media_type_count_amount_arr.filter(item => item.media_type_id !== 1).length === 0
      } else {
        return false
      }
    },
    // 计算两个日期之间的多少天
    totalDay() { return this.getDaysBetween(this.cuForm.actual_execute_time_start, this.cuForm.actual_execute_time_end) }
  },
  watch: {
    'cuForm.mediaDetailList': {
      handler(selfMediaArr) {
        let money = 0
        let tmp_price = 0
        let amount = 0
        if (selfMediaArr && selfMediaArr.length > 0) {
          selfMediaArr.forEach(tmp => {
            if (tmp.quantity !== null && tmp.amount !== null && tmp.media_cycle != null && tmp.media_cycle_unit != null) {
              tmp.price = divide(tmp.amount,multiply(tmp.quantity,tmp.media_cycle)).toFixed(2)
              if (tmp.contract_price != tmp.price){
                tmp.class_name = 'el-input__red'
              }else {
                tmp.class_name = ''
              }
              money = add(tmp.amount, money)
              let media_type_price = this.mediaTypeSpecPriceArr.filter(item => item.media_type_id == tmp.media_type_id)
              if (media_type_price && media_type_price.length > 0){
                let media_price = media_type_price[0]
                if (tmp.media_cycle_unit === 'day') {
                  if (media_price.price_day != null){
                    amount = add(amount, media_price.price_day * tmp.media_cycle * tmp.quantity)
                  }
                } else if (tmp.media_cycle_unit === 'week' ) {
                  if (media_price.price_week != null){
                    amount = add(amount, media_price.price_week * tmp.media_cycle * tmp.quantity)
                  }
                } else {
                  if (media_price.price_month != null){
                    amount = add(amount, media_price.price_month * tmp.media_cycle * tmp.quantity)
                  }
                }
              }
            }
          })
        }
        // 自营执行金额
        this.cuForm.self_execute_amount = money
        if (amount != 0 && amount != null){
          this.cuForm.discount = multiply(divide(money, amount),100).toFixed(2)
        }
        // 计算执行金额
        if (this.cuForm.self_execute_amount != null && this.cuForm.proxy_execute_amount != null){
          this.cuForm.release_amount = this.cuForm.self_execute_amount + this.cuForm.proxy_execute_amount
          this.cuForm.execute_amount = this.cuForm.self_execute_amount + this.cuForm.proxy_execute_amount
        }
      },
      deep: true
    },
    'cuForm.proxyMediaDetailList': {
      handler(proxyMediaArr) {
        let money = 0
        let tmp_price = 0
        if (proxyMediaArr && proxyMediaArr.length > 0) {
          proxyMediaArr.forEach(tmp => {
            if (tmp.proxy_quantity !== null && tmp.proxy_amount !== null && tmp.proxy_media_cycle != null) {
              tmp_price = divide(tmp.proxy_amount,multiply(tmp.proxy_quantity,tmp.proxy_media_cycle)).toFixed(2)
              tmp.proxy_price = tmp_price
              money = add(tmp.proxy_amount, money)
            }
          })
        }
        // 代理执行金额
        this.cuForm.proxy_execute_amount = money
        // 计算执行金额
        if (this.cuForm.self_execute_amount != null && this.cuForm.proxy_execute_amount != null){
          this.cuForm.release_amount = this.cuForm.self_execute_amount + this.cuForm.proxy_execute_amount
          this.cuForm.execute_amount = this.cuForm.self_execute_amount + this.cuForm.proxy_execute_amount
        }
      },
      deep: true
    },
    contractMediaDetailList: {
      handler(contractMediaDetailList) {
        let mediaTypeCount = []
        let mediaTypePrice = []
        let mediaTypeArr = []
        if (contractMediaDetailList && contractMediaDetailList.length > 0) {
          contractMediaDetailList.forEach(item => {
            if (item.media_type_id && !isNaN(item.quantity)){
              //let key = item.media_type_id+"_"+item.media_type_spec_id
              if (mediaTypeCount.hasOwnProperty(item.media_type_id)) {
                mediaTypeCount[item.media_type_id] += parseInt(item.quantity)
              } else {
                mediaTypeCount[item.media_type_id] = parseInt(item.quantity)
              }
            }
            if (item.media_type_id && !isNaN(item.price)){
              //let key = item.media_type_id+"_"+item.media_type_spec_id
              mediaTypePrice[item.media_type_id] = parseInt(item.price)
            }
          })
          this.contractMediaTypeCount = mediaTypeCount
          this.contractMediaTypePrice = mediaTypePrice
          // if (this.mediaTypeArr){
          //   this.mediaTypeArr.forEach((item, index) => {
          //     if (mediaTypeCount.hasOwnProperty(item.id)){
          //       mediaTypeArr.push(item)
          //     }
          //   })
          //   this.mediaTypeArr = []
          //   this.mediaTypeArr = mediaTypeArr
          // }
        }
      },
      deep: true
    },
    contractProxyMediaDetailList: {
      handler(billSaleProxyList) {
        let amount = 0
        if (this.media_type_count_amount_arr && this.media_type_count_amount_arr.length > 0) {
          this.media_type_count_amount_arr.forEach(item => {
            if (item.amount && !isNaN(item.amount)) {
              amount = add(parseInt(item.amount), amount)
            }
          })
        }
        if (billSaleProxyList && billSaleProxyList.length > 0) {
          billSaleProxyList.forEach(item => {
            if (item.proxyMediaDetailList && item.proxyMediaDetailList.length > 0) {
              item.proxyMediaDetailList.forEach(tmp => {
                if (tmp.fill_amount && !isNaN(tmp.fill_amount)) {
                  amount = add(parseInt(tmp.fill_amount), amount)
                }
              })
            }
          })
        }
        if (this.execute_amount !== null && this.execute_amount !== undefined && amount !== 0) {
          const tmp = divide(this.execute_amount, amount).toFixed(4)
          this.cuForm.discount = multiply(tmp, '100')
        } else {
          this.cuForm.discount = 0
        }
      },
      deep: true
    }
  },
  async created() {
    const uuid = this.$route.query.uuid
    const params = this.$store.state.keep.pageParamsMap.get(uuid)
    this.params = params
    this.initCompanyArr()
    this.initMediaTypeArr()
    this.initMediaTypeSpecPriceArr()
    if (params) {
      if (params.type !== undefined) {
        this.type = params.type
      }
      if (params.id || params.handle_param) {
        let id = null
        if (params.id) {
          id = params.id
        } else {
          id = params.handle_param.id
        }
        this.formLoading = true

        await cancelDetail({id: id}).then(rs => {
          this.cuCancel = rs.data
          detailNew({ id: rs.data.bill_sale_id }).then(res => {
            this.cuForm = res.data
            this.type = res.data.type
            this.totalExecutedAmount = res.data.total_executed_amount
            this.cuForm.total_executed_amount = this.totalExecutedAmount
            this.$set(this.cuForm, 'mediaDetailList', cloneDeep(this.cuForm.mediaDetailList))
            this.$set(this.cuForm, 'proxyMediaDetailList', cloneDeep(this.cuForm.proxyMediaDetailList))
          })
        })

        const flowStatus = this.cuForm.flow_status
        if (flowStatus == 3 || flowStatus == 4) {
          this.initCustomerArr()
        } else {
          this.initCustomerArr(true)
        }
        await listByCustomerId({ customerId: this.cuForm.customer_id }).then(res => {
          this.contractArr = res.data
        })
        this.cuForm.contract = this.contractArr.find(item => item.id === this.cuForm.contract_id)
        this.contractAmount = ((this.cuForm.contract || {}).discounted_price || 0)
        this.formLoading = false
      }
    }
  },
  methods: {
    // 初始化客户列表
    initCustomerArr(flag = false) {
      if (flag) {
        list_all().then(res => {
          this.customerArr = res.data
        })
      } else {
        company_list_all().then(res => {
          this.customerArr = res.data
        })
      }
    },
    // 客户选择框改变
    customerChange(id) {
      this.clearContractId()
      listByCustomerId({ customerId: id }).then(res => {
        this.contractArr = res.data
      })
    },
    // 合同客户名称change事件
    contractChange(data) {
      // 确定操作
      this.cuForm.dept_id = data.part_b_id
      this.cuForm.contract_id = data.id
      this.cuForm.contract_num = data.contract_num
      this.contractAmount = data.discounted_price
      this.contractMediaDetailList = []
      this.contractProxyMediaDetailList = []
      this.cuForm.mediaDetailList = []
      this.cuForm.proxyMediaDetailList = []
      // 合同详情
      contractDetail(data.id).then(res => {
        this.contractMediaDetailList = res.data.mediaDetailList
        this.contractProxyMediaDetailList = res.data.proxyMediaDetailList
        this.totalExecutedAmount = res.data.totalExecutedAmount
        this.cuForm.total_executed_amount = res.data.totalExecutedAmount
      })
    },
    // 清空合同
    clearContractId() {
      this.contractArr = []
      this.cuForm.contract = null
      this.cuForm.contract_id = null
      this.cuForm.contract_num = null
      this.cuForm.total_executed_amount = null
      this.cuForm.self_execute_amount = null
      this.cuForm.proxy_execute_amount = null

      this.contractAmount = null
      this.contractMediaDetailList = []
      this.contractProxyMediaDetailList = []
      this.totalExecutedAmount = null
    },
    // 初始化子公司数组
    initCompanyArr() {
      get_company().then(res => {
        this.companyArr = res.data
      })
    },
    // 初始化媒体类型
    initMediaTypeArr() {
      list_media_types().then(
        res => {
          this.mediaTypeArr = res.data
        }
      )
    },
    // 初始化媒体类型
    initMediaTypeSpecPriceArr() {
      list_media_type_spec_price().then(
        res => {
          this.mediaTypeSpecPriceArr = res.data
        }
      )
    },
    // 选择媒体类型 CHANGE 事件
    mediaTypeChange(index, mediaTypeId) {
      this.cuForm.mediaDetailList[index].media_type_spec_id = null
      if (this.contractMediaTypeCount.hasOwnProperty(mediaTypeId)){
        this.$set(this.cuForm.mediaDetailList[index],'contract_quantity',this.contractMediaTypeCount[mediaTypeId])
        this.cuForm.mediaDetailList[index].contract_quantity = this.contractMediaTypeCount[mediaTypeId]
      }

      if (this.contractMediaTypePrice.hasOwnProperty(mediaTypeId)){
        this.$set(this.cuForm.mediaDetailList[index],'contract_price',this.contractMediaTypePrice[mediaTypeId])
        this.cuForm.mediaDetailList[index].contract_price = this.contractMediaTypePrice[mediaTypeId]
      }

      listTypeSpecByMediaTypeId({ mediaTypeId }).then(res => {
        res.data.push('无')
        this.cuForm.mediaDetailList[index].media_type_spec_arr = res.data
      })
    },
    // 选择媒体类型规格 CHANGE 事件
    mediaTypeSpecChange(index, mediaTypeSpecId){
      // let key = this.cuForm.mediaDetailList[index].media_type_id + "_" + mediaTypeSpecId
      let key = this.cuForm.mediaDetailList[index].media_type_id
      if (this.contractMediaTypeCount.hasOwnProperty(key)){
        this.cuForm.mediaDetailList[index].contract_quantity = this.contractMediaTypeCount[key]
      }
    },
    // 执行时间 change 事件
    executeTimeChange(val,tmp){
      if (val){
        tmp.execute_time_start = val[0]
        tmp.execute_time_end = val[1]
      }
    },
    /**
     * 检验金额
     * @returns {boolean}
     */
    handlerCheck() {
      // 校验物品金额和消费金额
      const reg = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/
      let number = 0

      if (!(this.cuForm.hasOwnProperty('proxyMediaDetailList') && (this.cuForm.proxyMediaDetailList != null || (this.cuForm.proxyMediaDetailList instanceof Array && this.cuForm.proxyMediaDetailList.length > 0))) && !(this.cuForm.hasOwnProperty('mediaDetailList') && (this.cuForm.mediaDetailList != null || (this.cuForm.mediaDetailList instanceof Array && this.cuForm.mediaDetailList.length > 0)))) {
        this.$message.error('自营和代理资源至少添加一个')
        return false
      }

      if (this.cuForm.need_replace) {
        if (this.cuForm.item_amount) {
          if (!reg.test(this.cuForm.item_amount)) {
            this.$message.error('物品金额不合法')
            return false
          }
          number = add(number, this.cuForm.item_amount)
        }

        if (this.cuForm.cash_amount) {
          if (!reg.test(this.cuForm.cash_amount)) {
            this.$message.error('现金金额不合法')
            return false
          }
          number = add(number, this.cuForm.cash_amount)
        }
        if (this.cuForm.execute_amount < number) {
          this.$message.error('现金金额加上物品金额不能大于本次执行金额,请调整')
          return false
        }
      }
      if (this.cuForm.execute_amount + this.totalExecutedAmount > this.contractAmount){
        this.$message.error('本次发布金额与累计金额之和不能大于合同总金额,请调整！')
        return false
      }
      // 校验代理信息
      let sum = 0
      if (this.cuForm.hasOwnProperty('proxyMediaDetailList') && (this.cuForm.proxyMediaDetailList != null || (this.cuForm.proxyMediaDetailList instanceof Array && this.cuForm.proxyMediaDetailList.length > 0))) {
        for (let i = 0; i < this.cuForm.proxyMediaDetailList.length; i++) {
          const tmp = this.cuForm.proxyMediaDetailList[i]
          if (!isNaN(tmp.proxy_amount) && tmp.proxy_amount) {
            sum = add(sum, tmp.proxy_amount)
          }
        }
      }

      let sum2 = 0
      if (this.cuForm.hasOwnProperty('mediaDetailList') && (this.cuForm.mediaDetailList != null || (this.cuForm.mediaDetailList instanceof Array && this.cuForm.mediaDetailList.length > 0))) {
        this.cuForm.mediaDetailList.forEach(item => {
          if (!isNaN(item.amount) && item.amount) {
            sum2 = add(sum2, item.amount)
          }
        })
      }

      let sum3 = add(sum2, sum);
      if (sum3 == this.execute_amount) {
        return true
      } else {
        this.$message.error('【代媒体形式的媒体总金额：'+sum+'元】加上【媒体形式总额：'+sum2+'元】不等于【执行金额：'+this.execute_amount+'元】，请调整')
        return false
      }
    },
    save() {
      if ((this.cuForm.release_amount == null || this.cuForm.release_amount == '') && (this.cuForm.replace_amount == null || this.cuForm.replace_amount == '')) {
        this.$message.error('发布金额和换画金额不能都为空')
        return
      }
      if (this.handlerCheck()) {
        let flag = false
        if (!this.cuForm.is_old_data) {
          flag = this.check()
        } else {
          flag = true
        }
        if (flag) {
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const req = cloneDeep(this.cuForm)
          req.type = this.type
          // if (!this.onlyElevatorSmartFrame) {
          //   req.billSaleMediaCycleDTO = cloneDeep(this.cuForm.billSaleMediaCycle)
          // }
          saveNew(req).then(res => {
            if (res.data == null) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.closeThisPage()
            }
            loading.close()
          }).catch(() => {
            loading.close()
          })
        }
      }
    },
    lookMarketDetail(id,isView){
      let uuid = generateUUID()
      if (isView){
        this.$store.commit('keep/PUT_PAGE_PARAMS', {
          uuid: uuid,
          data: {
            id: id
          }
        })
        if (id >= 644){
          this.$router.push({
            name: 'look_market_order_detail_new',
            query: {
              uuid
            }
          })
        }else {
          this.$router.push({
            name: 'look_market_order_detail',
            query: {
              uuid
            }
          })
        }
      } else {
        this.$store.commit('keep/PUT_PAGE_PARAMS', {
          uuid: uuid,
          data: {
            is_create: true,
            type: this.type,
            bill_sale_id: this.saleBillId
          }
        })
        this.$router.push({
          name: 'create_market_order_new',
          query: {
            uuid
          }
        })
      }
    },
    toCreateMarketBill(bill_sale_id) {
      let uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          is_create: true,
          type: this.type,
          bill_sale_id: bill_sale_id
        }
      })
      this.$router.push({
        name: 'create_market_order_new',
        query: {
          uuid
        }
      })
    },
    submit() {
      if ((this.cuForm.release_amount == null || this.cuForm.release_amount === '') && (this.cuForm.replace_amount == null || this.cuForm.replace_amount === '')) {
        this.$message.error('发布金额和换画金额不能都为空')
        return
      }
      if (this.handlerCheck()) {
        let flag = false
        if (!this.cuForm.is_old_data) {
          flag = this.check()
        } else {
          flag = true
        }
        if (flag) {
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const req = cloneDeep(this.cuForm)
          req.type = this.type
          beginNew(req).then(res => {
            if (res.code == 200 && res.data.sale_bill_id > 0){
              this.$confirm(`销售单创建成功，您需要立即创建市场单吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // 确定操作
                this.toCreateMarketBill(res.data.sale_bill_id)
                // 关闭当前页面
                this.closeThisPage()
              }).catch(() => {
                // 取消操作
                this.$message({
                  type: 'info',
                  message: '已取消'
                })
              })
            }
            loading.close()
          }).catch(() => {
            loading.close()
          })
        }
      }
    },
    pass(opinion) {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      cancelPass({
        id: this.cuCancel.id,
        wf_check_opinion: opinion
      }).then(res => {
        this.closeThisPage()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    reject(opinion) {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      cancelReject({ id: this.cuCancel.id, wf_check_opinion: opinion }).then(res => {
        this.closeThisPage()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    remove() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      remove({ id: this.cuForm.id }).then(res => {
        this.closeThisPage()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    actualDelete() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      actual_delete({ id: this.cuForm.id }).then(res => {
        this.closeThisPage()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    closeThisPage() {
      this.$store.dispatch('tagsView/closeCurPage')
    },
    /**
     * 获取时间间隔 开始日期也算一天
     * @param startDate
     * @param endDate
     * @returns {number}
     */
    getDaysBetween(startDate, endDate) {
      const number = getDaysBetween(startDate, endDate) + 1
      return isNaN(number) ? '选择方案后自动计算' : number
    },
    /**
     * 填写金额改变时修改对应类型的值
     * @param item
     * @param type
     * @param fill_amount
     */
    fillAmountChange(item, type, fill_amount) {
      if (fill_amount) {
        // 计算出每天的价格
        const time = this.getDaysBetween(this.cuForm.actual_execute_time_start, this.cuForm.actual_execute_time_end)
        let num = divide(fill_amount, multiply(item.media_count, time))
        if (num.toString().indexOf('.') > -1) {
          num = parseFloat(num.toString().substr(0, num.toString().indexOf('.') + 5))
        }
        if (type === 'day') {
          item.day_price = num.toFixed(2)
          return item.day_price
        } else if (type === 'week') {
          item.week_price = multiply(num, 7).toFixed(2)
          return item.week_price
        } else {
          item.month_price = multiply(num, 30).toFixed(2)
          return item.month_price
        }
      } else {
        return null
      }
    },
    showContractDialog() {
      this.$refs.contractDialog.open()
    },
    check() {
      // if (this.onlyElevatorSmartFrame) {
      //   return true
      // } else {
      //   for (let i = 0; i < this.media_type_count_amount_arr.length; i++) {
      //     if (!this.media_type_count_amount_arr[i].amount) {
      //       this.$message.error('刊例总价有媒体类型的价格为空，请先设置周期')
      //       return false
      //     }
      //   }
      //   return true
      // }
      return true
    },
    // 自营资源添加
    selfMediaAdd() {
      if (this.cuForm.contract_id == null){
        this.$message.error('请先选择合同！')
        return false;
      }
      if (!this.cuForm.hasOwnProperty('mediaDetailList')) {
        this.$set(this.cuForm, 'mediaDetailList', [])
      }
      this.cuForm.mediaDetailList.push({
        media_type_id: null,
        media_type_spec_arr: [],
        media_type_spec_id: null,
        media_cycle: null,
        media_cycle_unit: null,
        duration: null,
        execute_time_start: null,
        execute_time_end: null,
        contract_quantity: null,
        quantity: null,
        total_executed_quantity: null,
        contract_price: null,
        price: null,
        amount: null,
        is_market: 0,
        class_name: ''
      })
    },
    /**
     * 自由资源删除
     * @param index
     */
    selfMediaDeleteByIndex(index) {
      this.cuForm.mediaDetailList.splice(index, 1)
    },
    // 代理媒体增加
    proxyMediaAdd() {
      if (this.cuForm.contract_id == null){
        this.$message.error('请先选择合同！')
        return false;
      }
      if (!this.cuForm.hasOwnProperty('proxyMediaDetailList')){
        this.$set(this.cuForm, 'proxyMediaDetailList', [])
      }
      this.cuForm.proxyMediaDetailList.push({
        proxy_media_type: null,
        proxy_media_type_spec: null,
        duration: null,
        proxy_media_cycle: null,
        proxy_media_cycle_unit: null,
        execute_time_start: null,
        execute_time_end: null,
        proxy_company_name: null,
        proxy_quantity: null,
        proxy_price: null,
        proxy_amount: null,
        is_market:0
      })
    },
    proxyMediaDeleteByIndex(index) {
      this.cuForm.proxyMediaDetailList.splice(index, 1)
    },
  }
}
</script>

<style scoped>

div /deep/ .el-input__red{
  border:1px solid red;
}

.mailTable {
  width: 90%;
  font-size: 14px;
  margin: 0 auto 10px auto;
  border-collapse: collapse;
}

.mailTable tr td {
  height: 50px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
  text-align: center;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.mailTable tr td.column {
  text-align: center;
  /*border: 1px solid #8c939d;*/
}

.header {
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  margin: 10px auto;
}

.color_self{}
.color_self input{color: red;}


.tip {
  color: red;
}

/deep/ .mailTable .el-form-item {
  margin-bottom: 0;
}

/deep/ .mailTable .el-form-item__content {
  line-height: 0;
}

.tip_td {
  width: 10% !important;
  padding: 0 20px !important;
  background-color: #F5F7FA;
  font-weight: bold;
}

.proxyTable {
  width: 100%;
  font-size: 12px;
}

.proxyTable tr td {
  line-height: 23px;
  padding: 6px 0;
  height: auto;
}

/deep/ .el-input.is-disabled .el-input__inner {
  background-color: white;
  color: black;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  background-color: white;
  color: black;
}

/deep/ .el-radio__input.is-disabled + span.el-radio__label {
  color: black;
}

/deep/ .el-radio__input.is-checked .el-radio__inner {
  border-color: #409EFF;
  background: #409EFF
}

/deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
  width: 4px;
  height: 4px;
  border-radius: 100%;
  background-color: #FFF;
}

.content_td {
  width: 40%;
}

@media screen and (max-width: 1920px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .mailTable {
    width: 95%;
    font-size: 14px;
    margin: 0 auto 10px auto;
    border-collapse: collapse;
  }
}

@media screen and (max-width: 1600px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .mailTable {
    width: 99%;
    font-size: 14px;
    margin: 0 auto 10px auto;
    border-collapse: collapse;
  }
}
.el-table .el-table__cell{
  padding: 0;
}
.el-table .cell, .el-table--border .el-table__cell:first-child .cell{
  padding: 0;
}
</style>
